package cn.aishua.ui;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.util.LinkedHashMap;

import org.apache.http.HttpResponse;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import cn.aishua.MyApplication;
import cn.aishua.R;
import cn.aishua.data.DataProvider;
import cn.aishua.data.DatabaseOperator;
import cn.aishua.network.HttpRequestUtil;
import cn.aishua.network.UpdateAppAsyncTask;
import cn.aishua.ui.myKaka.task.DataExchangeAsyncTask;
import cn.aishua.util.Constant;
import cn.aishua.util.NetworkState;
import cn.aishua.util.SharedPrefConst;

import com.baidu.mapapi.BMapManager;

public class SplashActivity
    extends Activity
{
    public static String dbFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/aishua";
    public static String dbFileName = dbFilePath + "/kaka.db";

    private MyHandler handler;

    private static final int START_LOCATION_SERVICE_AND_COPY_DB_FILE = 1;
    private static final int GET_RESOURCE = 2;
    private static final int GET_BANK_LIST = 3;

    //    private boolean isToDestroy = false;

    private TextView tvVersion;

    public static int DB_VERSION = 2;

    public static boolean MAIN_IS_IN_STACK;

    //    private boolean mapIsInitiated = false;

    public class MyHandler
        extends Handler
    {
        WeakReference<Activity> weakRef;

        private boolean task1 = false;
        private boolean task2 = false;
        private boolean task3 = false;
        private boolean task4 = false;

        MyHandler(Activity activity)
        {
            weakRef = new WeakReference<Activity>( activity );
        }

        public void handleMessage( Message msg )
        {
            switch( msg.what )
            {
                case START_LOCATION_SERVICE_AND_COPY_DB_FILE:
                    Log.d( "SplashActivity", "START_LOCATION_SERVICE_AND_COPY_DB_FILE has been done" );
                    task1 = true;
                    break;
                case GET_RESOURCE:
                    Log.d( "SplashActivity", "GET_RESOURCE has been done" );
                    task2 = true;
                    break;
                case GET_BANK_LIST:
                    Log.d( "SplashActivity", "GET_BANK_LIST is done" );
                    task3 = true;
                    break;
                case UpdateAppAsyncTask.UPDATE_DONE:
                    Log.d( "SplashActivity", "UPDATE_DONE is done" );
                    task4 = true;
                    break;
                default:
                    break;
            }

            if( task1 && task2 && task3 && task4 )
            {
                Activity activity = weakRef.get();
                //                Intent intent = new Intent( activity, MainActivity.class );
                Intent intent = new Intent( activity, MainActivityGroup.class );
                activity.startActivity( intent );
                activity.finish();
            }
        }
    };

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
    }

    protected void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.splash );

        // remove shared preference SHARED_PREF_BOOL_USER_IS_LOGIN 
        Editor editor = getSharedPreferences( "userInfo", Context.MODE_PRIVATE ).edit();
        editor.remove( SharedPrefConst.SHARED_PREF_BOOL_USER_IS_LOGIN );
        editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_LOGIN_IS_NOT_DONE, true );
        editor.putBoolean( SharedPrefConst.SHARED_PREF_BOOL_AUTO_IS_NOT_NEEDED, false );
        editor.commit();

        tvVersion = (TextView) findViewById( R.id.splash_tv_version );
        try
        {
            tvVersion.setText( "V " + getPackageManager().getPackageInfo( getPackageName(), 0 ).versionName );
        }
        catch( NameNotFoundException e )
        {
            Log.d( "SplashActivity", e.getMessage() );
        }

        // check network state
        if( !NetworkState.isAvailable( this ) )
        {
            Toast.makeText( this, "没有网络连接", Toast.LENGTH_SHORT ).show();
            return;
        }

        handler = new MyHandler( this );

        // task1: start location service and copy db file
        handler.postDelayed( new Runnable()
        {

            public void run()
            {
                BMapManager mBMapMan = new BMapManager( getApplicationContext() );
                mBMapMan.init( "FB72D11BBE6FECAAACC107735354B8E352B56DCB", null );
                ( (MyApplication) getApplication() ).setbMapMan( mBMapMan );

                copyDbFileToSDCard();
                // update db
                upgradeDatabase();

                handler.sendEmptyMessage( START_LOCATION_SERVICE_AND_COPY_DB_FILE );

            }

            private void upgradeDatabase()
            {
                SQLiteDatabase db = DatabaseOperator.getInstance().openDb();
                int localVersion = db.getVersion();
                if( DB_VERSION > localVersion ) // update is needed
                {
                    String tempTable = "fav_temp";
                    Log.d( "SplashActivity", "upgrade database from version " + localVersion + " to " + DB_VERSION );
                    //                    if( localVersion < 1 )
                    //                    {
                    //
                    //                        db.execSQL( "ALTER TABLE " + DatabaseOperator.TBL_NAME_FAVORITE + " ADD COLUMN picture blob" );
                    //                    }
                    //
                    //                    if( localVersion < 2 )
                    //                    {
                    db.execSQL( "create table " + tempTable
                        + " as select id,vendor_name, average_price, distance, tags, rebate from "
                        + DatabaseOperator.TBL_NAME_FAVORITE );
                    db.execSQL( "alter table " + tempTable + " add column pic_url text" );
                    db.execSQL( "drop table if exists " + DatabaseOperator.TBL_NAME_FAVORITE );
                    db.execSQL( "alter table " + tempTable + " rename to " + DatabaseOperator.TBL_NAME_FAVORITE );
                    //                    }

                    db.setVersion( DB_VERSION );
                }
                db.close();
            }
        }, 500 );

        // task2: get resource from server
        new DataExchangeAsyncTask( this, null )
        {

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().getResources();
            }

            @Override
            protected void handleSuccResponse( String strJson ) throws Exception
            {
                Constant.RESOURCE = strJson;
                handler.sendEmptyMessage( GET_RESOURCE );
            }
        }.execute();

        // task3: get bank list from server
        new DataExchangeAsyncTask( SplashActivity.this, null )
        {

            @Override
            protected HttpResponse sendRequest( String... params )
            {
                return HttpRequestUtil.getInstance().getBankList();
            }

            @Override
            protected void handleSuccResponse( String strJson ) throws Exception
            {
                Constant.BANK_ICON_MAP = new LinkedHashMap<String, String>();

                JSONObject jsonObj = new JSONObject( strJson );
                JSONArray array = jsonObj.getJSONArray( "cards" );
                if( array != null )
                {
                    int size = array.length();
                    for( int i = 0; i < size; i++ )
                    {
                        JSONObject item = array.getJSONObject( i );
                        String name = item.getString( "display_name" );
                        String logo = item.getString( "logo" );
                        Constant.BANK_ICON_MAP.put( name, logo );
                    }
                }
                handler.sendEmptyMessage( GET_BANK_LIST );

            }
        }.execute();

        // task4: check whether updating app is needed
        new UpdateAppAsyncTask( SplashActivity.this, handler ).execute();

        //Old cached picture data should be cleared.
        DataProvider.getInstance( this ).clearTempPic();
    };

    //    @Override
    //    protected void onPause()
    //    {
    //        super.onPause();
    //        isToDestroy = true; // next time, when some activity back to this splash activity, this splash activity will invoke finish()
    //    }
    //
    //    @Override
    //    protected void onResume()
    //    {
    //        super.onResume();
    //        if( isToDestroy )
    //        {
    //            finish();
    //        }
    //    }

    /**
     * copy the db file under asset into SD card
     */
    private void copyDbFileToSDCard()
    {
        Log.d( "KakaApplication", "load kaka.db... " );
        AssetManager assetManager = getAssets();
        InputStream cityInputStream = null;

        try
        {
            cityInputStream = assetManager.open( "kaka.db" );

            File dir = new File( dbFilePath );
            if( !dir.exists() )
            {
                dir.mkdir();
            }

            File dbFile = new File( dbFileName );

            //TODO remove later
            //            if( dbFile.exists() )
            //            {
            //                dbFile.delete();
            //            }

            if( !dbFile.exists() )
            {
                Log.d( "KakaApplication", "Copy db file from assets to SD card" );
                FileOutputStream cityOutPutStream = new FileOutputStream( dbFile );
                // copy file
                int b = 0;
                while( ( b = cityInputStream.read() ) != -1 )
                {
                    cityOutPutStream.write( b );
                }
            }
        }
        catch( IOException e )
        {
            Log.e( this.getClass().getSimpleName(), e.getMessage() );
        }
    }

}
